package com.wfk.h5.service;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wfk.constant.Constant;
import com.wfk.entity.Account;
import com.wfk.entity.Customer;
import com.wfk.entity.Items;
import com.wfk.enums.HandleType;
import com.wfk.service.IAccountService;
import com.wfk.service.IBaseInfoService;
import com.wfk.service.ICustomerService;
import com.wfk.service.IItemsService;
import com.wfk.utils.FunctionUtils;
import com.wfk.utils.ResponseData;
import com.wfk.utils.ValidateUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

@Service
public class BrushService {
	
	@Autowired
	private ICustomerService customerService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private IBaseInfoService baseInfoService;
	@Autowired
	private IItemsService itemsService;
	
	
	/**
	 * 广告扫描
	 * @param cid
	 * @param item
	 * @return
	 */
	public ResponseData handleBrush(Integer cid,Integer item){
		String startTime = this.baseInfoService.getByKey("startTime");
		String endTime = this.baseInfoService.getByKey("endTime");;
		int hour = DateUtil.hour(new Date(), true);
		if(hour<Integer.parseInt(startTime)||hour>Integer.parseInt(endTime)) {
			return ResponseData.baseError("浏览时间"+startTime+"点到"+endTime+"点");
		}
		if(cid==null) {
			return ResponseData.baseServiceError("登录超时请重新登录");
		}
		Items tems = itemsService.getById(item);
		if(item!=null){
			Customer cus = this.customerService.getById(cid);
			if(cus==null) {
				return ResponseData.baseServiceError("会员不存在");
			}else if(!ValidateUtil.isEquals(cus.getIsopen(),1)) {
				return ResponseData.baseServiceError("请先购买流量机");
			}
			BigDecimal randomMoney = RandomUtil.randomBigDecimal(new BigDecimal(baseInfoService.getByKey("minSerch")), new BigDecimal(baseInfoService.getByKey("maxSerch")));
			Account account = accountService.get(cid);
			if(BigDecimal.ZERO.compareTo(account.getMaxMoney())>=0) {
				return ResponseData.baseError("今日浏览已上限");
			}
			BigDecimal cost = FunctionUtils.mul(account.getMaxMoney(),randomMoney,2);
			if(BigDecimal.ZERO.compareTo(cost)>=0) {
				return ResponseData.baseError("今日浏览已上限");
			}else if(BigDecimal.ZERO.compareTo(FunctionUtils.sub(account.getSearchMoney(),cost,2))>0) {
				return ResponseData.baseError("今日浏览已上限");
			}
			String error = accountService.insertAccountDetail(cid, HandleType.brush.getId(),Constant.pay_in,cost,tems==null?"完成浏览任务奖金":"完成"+tems.getTitle().substring(0,5)+"浏览任务奖金");
			if(ValidateUtil.empty(error)) {
				return ResponseData.baseServiceError("操作失败").putDataValue("data",itemsService.itemsOne());
			}
			return ResponseData.ok().putDataValue("money",cost);
		}
		
		return ResponseData.ok().putDataValue("data",itemsService.itemsOne());
	}
	
}
